package com.cjm.algorithm.leetcode;

import com.cjm.algorithm.TreeNode;

public class IsBalanced110 {
    public static boolean isBalanced(TreeNode root) {
        return haha(root, 1).getBalance();
    }

    private static Balance haha(TreeNode root, int depth) {
        if (root == null) {
            return new Balance(true, depth);
        }
        depth++;
        Balance haha = haha(root.left, depth);
        if (!haha.getBalance()) {
            return haha;
        }
        Balance haha1 = haha(root.right, depth);
        if (!haha1.getBalance()) {
            return haha1;
        }
        if (Math.abs(haha.getDepth() - haha1.getDepth())>1) {
            return new Balance(false, 1);
        }
        int depth0 = haha.getDepth();
        int depth1 = haha1.getDepth();
        int depth2 = Math.max(depth1, depth0);
        return new Balance(true, depth2);
    }

    static class Balance {
        private Boolean balance;
        private int depth;

        public Balance(Boolean balance, int depth) {
            this.balance = balance;
            this.depth = depth;
        }

        public Boolean getBalance() {
            return balance;
        }

        public void setBalance(Boolean balance) {
            this.balance = balance;
        }

        public int getDepth() {
            return depth;
        }

        public void setDepth(int depth) {
            this.depth = depth;
        }
    }

    public static void main(String[] args) {
        System.err.println(isBalanced(TreeNode.generatorTreeNode(new Integer[]{3,9,20,null,null,15,7})));
        System.err.println(isBalanced(TreeNode.generatorTreeNode(new Integer[]{1,2,2,3,3,null,null,4,4})));
        System.err.println(isBalanced(TreeNode.generatorTreeNode(new Integer[]{})));
    }
}
